from machine import Pin
import utime
import network
import ntptime 
import time
from machine import RTC
from machine import Pin, I2C
from IIC256 import *
from sht20 import *
import PFC8563
import machine
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)  
rtc = RTC()
pin1 = Pin(12, Pin.OUT)
pin2 = Pin(13, Pin.OUT)
pin3 = Pin(22, Pin.OUT)
pin1.on()
pin2.off()
pin3.off()
def sync_ntp():
    global sta_if
    # ntptime.NTP_DELTA = 3155644800 # UTC+8 的 magic number
    ntptime.NTP_DELTA = 3155673600
    ntptime.host = 'ntp1.aliyun.com'
    for _ in  range(10):
        try:
            ntptime.settime()
        except:
            time.sleep(1)
            print(f"try ntptime {_} ")
            continue
        else:
            print(rtc.datetime())
            sta_if.active(False) 
            return True
    return False



#sta_if.connect("<AP_name>", "<password>") # Connect to an AP
def connectWifi():
    global sta_if
    sta_if.active(True) 
    n=0
    if not sta_if.isconnected():
        sta_if.connect("Network_1", "15368274761")
        # sta_if.connect("ChinaNet-5Wi4","twvey5ag")
        while not sta_if.isconnected():
            n=n+1
            print("connect...%02d"%(n))
            utime.sleep(1)
            if(n>=30):
                sta_if.active(False)
                return False
        print("connected")
def showSec(s):
    if(s%2==0):
        buf=i2c.readfrom(SHT20_address,3)
        t=buf[0]*256+buf[1]
        sht20=(t/65536*125)-6
        i2c.writeto(SHT20_address,bytearray(T_measurement))
        print(f"HR:{sht20:.2f}")
        print32(f"{sht20:.2f}%   ",0,12)
    else:
        buf=i2c.readfrom(SHT20_address,3)
        t=buf[0]*256+buf[1]
        sht20=(t/65536*175.72)-46.85
        i2c.writeto(SHT20_address,bytearray(RH_measurement))
        print(f"T:{sht20:.3f}")
        print32(f"{sht20:.2f}C   ",0,8)
    lprint(f"{s:02d}",72,1)
def f():
    i2c = I2C(1,scl=Pin(18), sda=Pin(19),freq=400000)
    i2c.scan()  
    LCDInit()
    lcdClean()
    # PFC8563.sync()
    da=showtimehm()
    sht20C()
    # f()
    for i in range(10):
        t=rtc.datetime()
        da=showtimehm()
        s=((da[0]>>4) * 10) + (da[0]&0x0f)
        showSec(s)
        utime.sleep_us(1000000-t[7])
    pin3.on()
    s=((da[0]>>4) * 10) + (da[0]&0x0f)
    while 1 :
        # showtimehm()

        t=rtc.datetime()
        print(t)
        print(int((1000000-t[7])/1000))
        # utime.sleep_us(1000000-t[7])
        machine.lightsleep(int((1000000-t[7])/1000)) 
        s+=1
        if(s>=60):
            da=showtimehm()
            s=((da[0]>>4) * 10) + (da[0]&0x0f)
        showSec(s)
            
        
def deepwake():
    while True:
        t=rtc.datetime()
        print(time.mktime(t))
        print("{0:0>2d}:{1:0>2d}:{2:0>2d}\t\t{3:0>3d}".format(t[4],t[5],t[6]))
        t=rtc.datetime()
        utime.sleep_us(1000000-t[7])
        print(int((1000000-t[7]))/1000)
def showtimehm():
    da=i2c.readfrom_mem(81,2,8)
    m=((da[1]>>4) * 10) + (da[1]&0x0f)
    h=((da[2]>>4) * 10) + (da[2]&0x0f)
    if(h==23 and m==11):
        PFC8563.sync()
        da=i2c.readfrom_mem(81,2,8)
    s=((da[0]>>4) * 10) + (da[0]&0x0f)
    m=((da[1]>>4) * 10) + (da[1]&0x0f)
    h=((da[2]>>4) * 10) + (da[2]&0x0f)
    d=((da[3]>>4) * 10) + (da[3]&0x0f)
    w=((da[4]>>4) * 10) + (da[4]&0x0f)
    mo=((da[5]>>4) * 10) + (da[5]&0x0f)
    y=((da[6]>>4) * 10) + (da[6]&0x0f)
    lprint(f"20{y:02d}-{mo:02d}-{d:02d}",72,3)
    lcdAddress(174,4,16,16)
    LDS(xj[7])
    lcdAddress(174+16,4,16,16)
    LDS(xj[8])
    lcdAddress(174+32,4,16,16)
    LDS(xj[w%7])
    printbignumber([(da[2]>>4),(da[2]&0x0f),10,(da[1]>>4),(da[1]&0x0f)])
    return da
if __name__ == "__main__":
    f()